//
//  SpeechManager.m
//  OC-Example
//
//  Created by apang on 2018/7/31.
//  Copyright © 2018年 apang.men All rights reserved.
//

#import "SpeechManager.h"

@interface SpeechManager ()<AVSpeechSynthesizerDelegate>

@property (nonatomic, strong) AVSpeechSynthesizer * speech;

@end

@implementation SpeechManager

+ (instancetype)shared {
    static SpeechManager * speechManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        speechManager = [[SpeechManager alloc] init];
    });

    return speechManager;
}

- (instancetype)init {

    self = [super init];

    if (self) {

        _speech= [[AVSpeechSynthesizer alloc] init];

        _speech.delegate = self;

        AVAudioSession *audioSession = [AVAudioSession sharedInstance];

        NSError *error;

        if (![audioSession setCategory:AVAudioSessionCategoryPlayback error:&error]) {
            NSLog(@"set category error : %@", error);
        }
        if (![audioSession setActive:YES error:&error]) {
            NSLog(@"set active error: %@", error);
        }

    }

    return self;
}

- (AVSpeechUtterance *)speechUtteranceWithStr:(NSString *)string {

    AVSpeechUtterance * spechUtterance = [AVSpeechUtterance speechUtteranceWithString:string];
    [spechUtterance setVoice:[self speechVoice]];
    return spechUtterance;
}
- (AVSpeechSynthesisVoice *)speechVoice{

    return [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
}
+ (void)speechWithString:(NSString *)string {

    [[SpeechManager shared] speechWithString:string];
}
- (void)speechWithString:(NSString *)string{
    if ([_speech isSpeaking]) {
        [self stopSpeaking];
    }
    [_speech speakUtterance:[self speechUtteranceWithStr:string]];
}
+(void)pauseSpeaking {

    [[SpeechManager shared] pauseSpeaking];
}
- (void)pauseSpeaking {

    [_speech pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];//立即停止不能使用一句
}

+ (void)continueSpeaking {

    [[SpeechManager shared] continueSpeaking];
}

- (void)continueSpeaking {

    [_speech continueSpeaking];
}

+ (void)stopSpeaking {

    [[SpeechManager shared] stopSpeaking];
}

- (void)stopSpeaking {
    
    [_speech stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
}
@end
